<script setup lang="ts">
import { ref, reactive, onMounted ,computed,nextTick} from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElInput, ElButton, } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import { getEmpProcessList,getProcessTemplateList,getBorrowerDetail,
  getBorrowerMaterialDetail,getAssetRepairDetail,getAssetReturnDetail } from "@/api/EmpProcessList.js"
import {Refresh, Search} from '@element-plus/icons-vue'
import Drawer from '@/components/Drawer.vue'
//tab选项卡
const activeName = ref("1")
const handleClick = (tab: TabsPaneContext, event: Event) => {
  //console.log(tab.props.label, tab.props.name)
  //searchParams.templateId = tab.props.name
  searchParams.processType = tab.props.label
  //加载数据
  loadData()
}
//定义Process接口
interface Process {
  id: number
}
interface ProcessTemplate {
  id: number
  templateName:string
}
// 表格数据
const tableData = ref([])
// 审批模板列表
const templateList = ref<ProcessTemplate[]>([])

// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchParams = reactive({
  processType: '资产借用申请', //审批类型
  type: 1,
  startUserName:"", //申请人
  beginTime:null, //申请开始时间
  endTime:null, //申请结束时间
  userId:4, //当前登录的用户id，测试数据
  status:null,
  handleBeginTime:null, //处理开始时间
  handleEndTime:null, //处理结束时间
  templateId:"", //模板id
})
// 搜索重置
const resetSearch = () => {
  searchParams.processType = ''
  searchParams.startUserName = ''
  searchParams.beginTime = null
  searchParams.endTime = null
  searchParams.status = null
  searchParams.handleBeginTime = null
  searchParams.handleEndTime = null

  loadData()
}
// 加载数据
const loadData = async () => {
  try {
    let data = {
      ...searchParams,
      ...pagination
    }
    // API调用
    getEmpProcessList(data).then(res=>{
      if (res.data[0]==null){
        tableData.value = null
        pagination.total =  0
      }else{
        tableData.value = res.data[0].list
        pagination.total =  res.data[0].total
      }
    })
  } catch (error) {
    console.error('数据加载失败')
  }
}
//查看详情
const showDetail = (row)=>{
  //alert(row.processType)
  showFormData.title  = row.processType
  if (row.processType.indexOf("耗材")>=0){
    getMaterialBorrowDetail(row.businessId,1) //获取耗材出库详情
  }else if(row.processType.indexOf("资产借用")>=0){
    getAssetBorrowerDetail(row.businessId,0) //获取资产借用详情
  }else if(row.processType.indexOf("资产报修")>=0){
    getAssetRepairDetailInfo(row.businessId) //获取资产报修详情
  }else if(row.processType.indexOf("资产归还")>=0){
    getAssetReturnDetailInfo(row.businessId) //获取归还报修详情
  }


}
const showFormData = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  expectedReturn: '',
  locationName: '',
  usagePurpose: '',
  operatorName:'',
  title:'',
  assets:[]
})

const formDataValues = computed( () => [
  {
    label: '出库编号:',
    value: showFormData.value.id
  },
  {
    label: '出库时间:',
    value: showFormData.value.createTime
  },
  {
    label: '借用人:',
    value: showFormData.value.username
  },
  {
    label: '借用人部门:',
    value: showFormData.value.deptName
  },
  {
    label: '经办人:',
    value: showFormData.value.operatorName
  },
  {
    label: '出库仓库:',
    value: showFormData.value.locationName
  },
  {
    label: '备注:',
    value: showFormData.value.usagePurpose
  }
])
//右侧抽屉
// 控制 Drawer 显示状态
const drawerVisible = ref(false)

// 耗材详情
const getMaterialBorrowDetail = (id,type) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getBorrowerMaterialDetail({id,type}).then(res => {
    if (res.code === 200) {
      //console.log(res,"详情数据")
      nextTick(() => {
        showFormData.value.id = res.data.id
        showFormData.value.createTime = res.data.createTime
        showFormData.value.username = res.data.username
        showFormData.value.deptName = res.data.deptName
        showFormData.value.expectedReturn = res.data.expectedReturn
        showFormData.value.locationName = res.data.locationName
        showFormData.value.usagePurpose = res.data.usagePurpose
        showFormData.value.operatorName = res.data.operatorName
        tableDataByDetail.value = res.data.materialBorrowVoList
        //console.log(formDataValues.value,6666)
      })
    }
  })
  drawerVisible.value = true
}

// tableData
const tableColumns = ref([
  { prop: 'code', label: '耗材编码' },
  { prop: 'name', label: '耗材名称' },
  { prop: 'categoryName', label: '耗材分类' },
  { prop: 'specification', label: '规格' },
  { prop: 'unit', label: '单位' },
  { prop: 'warehouseName', label: '出库仓库' },
  { prop: 'quantity', label: '当前库存' },
  { prop: 'materialNum', label: '出库数量' },
  { prop: 'materialDesc', label: '出库备注' },
])

const tableDataByDetail = ref([])

// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false
}

// 资产借用

const drawerVisibleByAssetBorrow = ref(false)
const showFormDataByAssetBorrow = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  expectedReturn: '',
  locationName: '',
  usagePurpose: '',
  assets:[]
})
const getAssetBorrowerDetail = (id,type) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getBorrowerDetail({id,type}).then(resp => {
    if (resp.code === 200) {
      //console.log(resp,"详情数据")
      nextTick(() => {
        showFormDataByAssetBorrow.value.id = resp.data.id
        showFormDataByAssetBorrow.value.createTime = resp.data.createTime
        showFormDataByAssetBorrow.value.username = resp.data.username
        showFormDataByAssetBorrow.value.deptName = resp.data.deptName
        showFormDataByAssetBorrow.value.expectedReturn = resp.data.expectedReturn
        showFormDataByAssetBorrow.value.locationName = resp.data.locationName
        showFormDataByAssetBorrow.value.usagePurpose = resp.data.usagePurpose
        tableDataByAssetBorrow.value = resp.data.assets
        //console.log(formDataValues.value,7777)
      })
    }
  })
  drawerVisibleByAssetBorrow.value = true
}


const formDataValuesByAssetBorrow = computed( () => [
  {
    label: '借用人部门:',
    value: showFormDataByAssetBorrow.value.deptName
  },
  {
    label: '借用人:',
    value: showFormDataByAssetBorrow.value.username
  },
  {
    label: '借用后位置:',
    value: showFormDataByAssetBorrow.value.locationName
  },
  {
    label: '备注:',
    value: showFormDataByAssetBorrow.value.usagePurpose
  },
  {
    label: '预计归还时间:',
    value: showFormDataByAssetBorrow.value.expectedReturn
  },
  {
    label: '创建时间:',
    value: showFormDataByAssetBorrow.value.createTime
  }
])



// tableData
const tableColumnsByAssetBorrow = ref([
  {prop: 'assetCode', label: '资产编码'},
  { prop: 'name', label: '资产名称' },
  { prop: 'categoryName', label: '资产分类' },
  { prop: 'model', label: '型号规格' },
  //{ prop: 'status', label: '状态' },
  // { prop: 'serialNumber', label: '序列号' },
  { prop: 'locationName', label: '位置' }
])
const tableDataByAssetBorrow = ref([])
// 关闭 Drawer 的方法
const closeDrawerByAssetBorrow = () => {
  drawerVisibleByAssetBorrow.value = false
}

// 资产报修详情
const drawerVisibleByAssetRepair = ref(false)
const showFormDataByAssetRepair = ref({
  id: '',
  createTime: "",
  username: '',
  deptName: '',
  locationName: '',
  faultDesc: '',
  assets:[]
})
const getAssetRepairDetailInfo = (id) => {
  getAssetRepairDetail(id).then(resp => {
    if (resp.code === 200) {
      console.log(resp,"详情数据")
      nextTick(() => {
        showFormDataByAssetRepair.value.id = resp.data.id
        showFormDataByAssetRepair.value.createTime = resp.data.createTime
        showFormDataByAssetRepair.value.username = resp.data.username
        showFormDataByAssetRepair.value.deptName = resp.data.deptName
        showFormDataByAssetRepair.value.locationName = resp.data.locationName
        showFormDataByAssetRepair.value.faultDesc = resp.data.faultDesc
        tableDataByAssetBorrow.value = resp.data.assets
      })
    }
  })
  drawerVisibleByAssetRepair.value = true
}
const formDataValuesByAssetRepair = computed( () => [
  {
    label: '维修编号:',
    value: showFormDataByAssetRepair.value.id
  },
  {
    label: '创建时间:',
    value: showFormDataByAssetRepair.value.createTime
  },
  {
    label: '报修人:',
    value: showFormDataByAssetRepair.value.username
  },
  {
    label: '报修人部门:',
    value: showFormDataByAssetRepair.value.deptName
  },
  {
    label: '送检地点:',
    value: showFormDataByAssetRepair.value.locationName
  },
  {
    label: '备注:',
    value: showFormDataByAssetRepair.value.faultDesc
  }
])
// 关闭 Drawer 的方法
const closeDrawerByAssetRepair = () => {
  drawerVisibleByAssetRepair.value = false
}

// 资产归还详情
const drawerVisibleByAssetReturn = ref(false)
const showFormDataByAssetReturn = ref({
  id: '',
  createTime: '',
  // username: '',
  deptName: '',
  locationName: '',
  usagePurpose: '',
  assets:[]
})
const getAssetReturnDetailInfo = (id) => {
  getAssetReturnDetail(id).then(resp => {
    if (resp.code === 200) {
      console.log(resp,"详情数据")
      nextTick(() => {
        showFormDataByAssetReturn.value.id = resp.data.id
        showFormDataByAssetReturn.value.createTime = resp.data.createTime
        showFormDataByAssetReturn.value.username = resp.data.username
        showFormDataByAssetReturn.value.deptName = resp.data.deptName
        showFormDataByAssetReturn.value.expectedReturn = resp.data.expectedReturn
        showFormDataByAssetReturn.value.locationName = resp.data.locationName
        showFormDataByAssetReturn.value.usagePurpose = resp.data.usagePurpose
        tableDataByAssetBorrow.value = resp.data.assets
      })
    }
  })
  drawerVisibleByAssetReturn.value = true
}
const formDataValuesByAssetReturn = computed( () => [
  {
    label:'归还编号',
    value: showFormDataByAssetReturn.value.id
  },
  {
    label: '归还时间',
    value: showFormDataByAssetReturn.value.createTime
  },
  // {
  //   label: '归还人员',
  //   value: showFormData.value.username
  // },
  {
    label: '归还后使用部门',
    value: showFormDataByAssetReturn.value.deptName
  },
  {
    label: '归还后位置',
    value: showFormDataByAssetReturn.value.locationName
  },
  {
    label: '备注',
    value: showFormDataByAssetReturn.value.usagePurpose
  }
])
// 关闭 Drawer 的方法
const closeDrawerByAssetReturn = () => {
  drawerVisibleByAssetReturn.value = false
}





// 生命周期钩子
onMounted(() => {
  loadData()
  getProcessTemplateList().then(res=>{
    templateList.value = res.data
    activeName.value = res.data[0].id
  })
})



</script>

<template>
  <div class="">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane v-for="template in templateList"
                   :label="template.templateName"
                   :name="template.id"
                   :key="template.id" ></el-tab-pane>
    </el-tabs>

    <el-form :inline="true" :model="queryForm" style="margin-top: 10px;">
      <el-form-item>
        <el-space>
        <el-input
          v-model="searchParams.startUserName"
          placeholder="请输入申请人"
          style="width: 230px; "
          clearable
          :prefix-icon="Search"
        />
          <el-select v-model="searchParams.status" placeholder="请选择审批状态"
                     style="width: 230px; " clearable>
            <el-option label="审批中" value="1"/>
            <el-option label="已通过" value="2"/>
            <el-option label="已撤回" value="3"/>
            <el-option label="已驳回" value="-1"/>
            <!-- 使用图标组件 -->
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-select>
          <el-date-picker
              v-model="searchParams.beginTime"
              type="date"
              placeholder="请选择申请开始日期"
              style="width: 230px; "
              clearable
          />
          -
          <el-date-picker
              v-model="searchParams.endTime"
              type="date"
              placeholder="请选择申请结束日期"
              style="width: 230px; "
              clearable
          />
        </el-space>
      </el-form-item>

      <el-form-item >
        <el-button type="primary" :icon="Search" @click="loadData">搜索</el-button>
        <el-button type="primary" plain :icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%;">
      <el-table-column prop="startDeptName" label="申请部门" width="150"/>
      <el-table-column prop="startUserName" label="申请人"  width="100"/>
      <el-table-column label="处理状态"   width="100">
        <template #default="scope">
          <el-tag class="mx-1" type="primary" v-if="scope.row.status==1">审批中</el-tag>
          <el-tag class="mx-1" type="success" v-if="scope.row.status==2">已通过</el-tag>
          <el-tag class="mx-1" type="warning" v-if="scope.row.status==3">已撤回</el-tag>
          <el-tag class="mx-1" type="danger" v-if="scope.row.status==-1">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="单据编号" align="center"/>
      <el-table-column prop="title" label="标题" align="center"/>
      <el-table-column prop="processType" label="类型" align="center"/>
      <el-table-column prop="createTime" label="申请时间" align="center" width="120"/>
      <el-table-column prop="description" label="当前节点" align="center"/>
      <el-table-column prop="handleTime" label="处理时间" align="center" width="120"/>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="showDetail(scope.row)"  >
            <el-icon><el-icon-edit /></el-icon>查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"

      :total="pagination.total"
      layout="slot, prev, pager, next"
      style="margin-top: 20px"
    >
      <el-text key="1">总条数：{{ pagination.total }}</el-text>
    </el-pagination>

    <!--------------- 耗材出库详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisible" :formData="showFormData" :title="'耗材出库详情'"
            :formDataValues="formDataValues" :tableColumns="tableColumns" :tableData="tableDataByDetail" @close="closeDrawer" />
    <!--------------- 资产借用详情抽屉 ----------------->
   <Drawer v-model:visible="drawerVisibleByAssetBorrow" :formData="showFormDataByAssetBorrow" :title="'资产借用详情'"
            :formDataValues="formDataValuesByAssetBorrow" :tableColumns="tableColumnsByAssetBorrow"
            :tableData="tableDataByAssetBorrow" @close="closeDrawerByAssetBorrow" />

    <!--------------- 资产报修详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisibleByAssetRepair" :formData="showFormDataByAssetRepair" :title="'资产报修详情'"
            :formDataValues="formDataValuesByAssetRepair" :tableColumns="tableColumnsByAssetBorrow"
            :tableData="tableDataByAssetBorrow" @close="closeDrawerByAssetRepair" />
    <!--------------- 资产归还详情抽屉 ----------------->
    <Drawer v-model:visible="drawerVisibleByAssetReturn" :formData="showFormDataByAssetReturn" :title="'资产归还详情'"
            :formDataValues="formDataValuesByAssetReturn" :tableColumns="tableColumnsByAssetBorrow"
            :tableData="tableDataByAssetBorrow" @close="closeDrawerByAssetReturn" />

  </div>
</template>

<style scoped>
.page-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>